<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<link rel="stylesheet" type="text/css" href="./scripts/estilo.css" />
		<title>Castrucci Maps - 2010 Beta Test</title>
		<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA9N7ZgI7iRfg1ef5wnMehwRRHIZ64MQDS_PgfLYruevxWF5hHaxSR5O8sCmzo1VF6Jo25Txzo3miAig" type="text/javascript"></script>
		<script src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0" type="text/javascript"></script>
		<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script> 
		<script type="text/javascript">
			function initialize()
			{
				if (GBrowserIsCompatible())
				{
					//Define a largura da janela.
					var width = (parseInt(document.documentElement.clientWidth)-40);
					//Define a altura da janela.
					var height = (parseInt(document.documentElement.clientHeight)-30);
					//Define a posicao inicial do mapa.
					var pos_inicial = new GLatLng(-23.9675717, -46.3878558);
					//var pos_inicial = new GLatLng(47.613224, -122.34623);
					
					// Define Maps Settings
					var geocoder = new GClientGeocoder();
					var map = new GMap2(document.getElementById("map_canvas"), {size: new GSize(width,height)});
					
					//map.setUIToDefault();
					map.setMapType(G_NORMAL_MAP);
					map.setCenter(pos_inicial,14);
					map.addControl(new GLargeMapControl());
					map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5,20)));
					
					// Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
					var icon = new GIcon(G_DEFAULT_ICON);
					icon.iconSize = new GSize(75, 55);
					icon.iconAnchor = new GPoint(10, 30);
					icon.infoWindowAnchor = new GPoint(9, 2);
					
					/*
					var pos_semaforo = new GLatLng(-23.9689294, -46.3230787);
					var pos_stop = new GLatLng(-23.9685581, -46.3230787);
					map.addOverlay(createMarker(pos_stop));
					map.addOverlay(createMarker2(pos_semaforo));
					*/
					
					GEvent.addListener(map, "click", getAddress);
					
					function getAddress(overlay, pos_inicial) 
					{
						if (pos_inicial != null) 
						{
							var address = pos_inicial;
							geocoder.getLocations(pos_inicial, showAddress);
						}
					}
					
					function showAddress(response) 
					{
						//map.clearOverlays();
						if (!response || response.Status.code != 200) 
						{
							alert("Status Code:" + response.Status.code);
						} 
						else 
						{
							place = response.Placemark[0];
							//point = new GLatLng('-23.961835', '-46.323907');
							point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
							marker = new GMarker(point);
							map.addOverlay(marker);
							//map.addOverlay(createMarker(pos_stop));
							marker.openInfoWindowHtml(
									'<b>Posição Desejada:</b>' + response.name + '<br/>' + 
									'<b>Posição Aproximada:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
									'<b>Endereço Aproximado:</b>' + place.address + '<br>' +
									'<br>' + '.');							
						}
					}
					
					var encodedPolyline = new GPolyline.fromEncoded(
					{
						color: "red",
						weight: 10,
						points: "rshqC|u~yG~JjWoJlT~DnDuHzGcChMC|Psi@hsAeFrcA}z@jo@",
						levels: "BBBBBBBBBB",
						zoomFactor: 32,
						numLevels: 4
					}
					);
					//map.addOverlay(encodedPolyline);								
				}
			}	
			GSearch.setOnLoadCallback(initialize);			
 </script>
	</head>
	<body onload="initialize()" onunload="GUnload()">
		<p>
			<?php
				define("MAPS_HOST", "maps.google.com.br");
				define("KEY", "ABQIAAAA9N7ZgI7iRfg1ef5wnMehwRRHIZ64MQDS_PgfLYruevxWF5hHaxSR5O8sCmzo1VF6Jo25Txzo3miAig");

				// Opens a connection to a MySQL server
				$connection = mysql_connect("localhost", "root", "");		
				if (!$connection)	{
					die("Not connected : " . mysql_error());
				}

				// Set the active MySQL database
				$db_selected = mysql_select_db("maps1", $connection);
				if (!$db_selected) {
					die("Can\'t use db : " . mysql_error());
				}

				// Select all the rows in the markers table
				$query = "select * from markers order by id asc";
				
				$result = mysql_query($query);
				if (!$result) {
					die("Invalid query: " . mysql_error());
				}

				// Initialize delay in geocode speed
				$delay = 0;
				$base_url = "http://" . MAPS_HOST . "/maps/geo?output=csv&key=" . KEY;

				// Iterate through the rows, geocoding each address
				
				while ($row = @mysql_fetch_assoc($result)) {
					$geocode_pending = true;
					while ($geocode_pending) {
						$id = $row["id"];
						$name = $row["name"];
						$address = $row["address"];
						$request_url = $base_url . "&q=" . urlencode($address);
						$csv = file_get_contents($request_url) or die("url not loading");

						$csvSplit = explode(",", $csv);
						$status = $csvSplit[0];
						$lat = $csvSplit[2];
						$lng = $csvSplit[3];
						if (strcmp($status, "200") == 0) {
							// successful geocode
							$geocode_pending = false;
							$lat = $csvSplit[2];
							$lng = $csvSplit[3];

							$query = sprintf("UPDATE markers " .
										 " SET lat = '%s', lng = '%s' " .
										 " WHERE id = %s LIMIT 1;",
										 mysql_real_escape_string($lat),
										 mysql_real_escape_string($lng),
										 mysql_real_escape_string($id));
							$update_result = mysql_query($query);
/*							
							//echo "Vai gravar AGORA: " . $name . "<br>";
							echo "Endereço" . "(".$id."): " . $address . "<br>";
							echo "Coordernadas... Lat: " . $lat . " / "  . "Long: " . $lng . "<hr>";
	*/						//echo "Received status: " . $status . "<hr>";
							
							if (!$update_result) {
								die("Invalid query: " . mysql_error());
							}
						} 
						else if (strcmp($status, "620") == 0) {
							// sent geocodes too fast
							$delay += 100000;
						} 
						else {
							// failure to geocode
							$geocode_pending = false;
							echo "Address " . $address . " failed to geocoded. ";
							echo "Received status " . $status . "\n";
						}
						usleep($delay);
					}
				}
				
			?>
		</p>
		<hr>
		<div class="map" id="map_canvas"></div>
	</body>
</html>